Performance
When learning about array iteration methods like forEach
and map
, you might hear that they're slow. For example, some will say that a for
loop performs the same task much more quickly:
const students = [ { name: 'Aisha', grade: 89 }, { name: 'Bruno', grade: 55 }, { name: 'Carlos', grade: 68 }, { name: 'Dacian', grade: 71 }, { name: 'Esther', grade: 40 },];
const passedStudentNames = [];
for (let i = 0; i < students.length; i++) { const student = students[i];
if (student.grade >= 60) { passedStudentNames.push(student.name); }}
Is this method faster? Well, it's hard to say; JavaScript engines are always being optimized, and it can be really surprising which methods are slow and which methods are fast. The answer is always changing, and it probably varies between browsers. But, honestly, it doesn't matter.
When people say that for
loops are faster than array method equivalents, they generally share some benchmarks that prove it. Those benchmarks typically iterate over tens of millions of items. If your data set is only 1000 or 10,000 items long, both approaches will round to zero milliseconds.
And when we work on the front-end, we're never working with millions of items. Let's say we're building a search results page. We might show 10 or 20 or 100 items, but we're never going to show millions. In order for us to show an item to the user, we need to fetch it from the backend API. And if we tried to fetch millions of items from the API, the request would take forever, and we'd probably run out of local memory.
Let's be generous, and say that the API sends data on 1000 items. Even a 10-year-old budget smartphone can iterate over 1000 items in less than a millisecond, no matter which method you choose. JavaScript is an optimized language, and even low-end devices should be able to manage millions of operations a second.
The for
loop approach might be twice as fast, but if both options finish in less than a millisecond, it really doesn't matter. Humans can't perceive time differences at this scale.
When it comes to front-end web performance, we have other concerns that affect the user experience to a much larger degree. This is things like making sure our CSS animations are well-optimized, shrinking the size of our static assets, lazy-loading JS code that isn't needed right away, using virtualization, things like that.